﻿using CosenSecurity;
using Newtonsoft.Json;
using System;
using System.Web;
using System.Web.Security;
using Easy.BLL;
using Easy.Model;

namespace Easy.Web
{
    public partial class login : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request["applogin"] != null)
            {
                string empno = Request["empno"];
                string pwd = Request["pwd"];
                string loginMsg = (new SystemUserManager()).Login(empno, pwd);
                Controls.Clear();
                if (string.IsNullOrWhiteSpace(loginMsg))
                {
                    Response.Write("{\"LoginResult\":\"Success\"}");
                }
                else
                {
                    Response.Write("{\"LoginResult\":\"" + loginMsg + "\"}");
                }
            }
            else
            {
                string logout = "";
                if (Context.Request["logout"] == "1")
                {
                    FormsAuthentication.SignOut();
                    logout = "&logout=1";
                }
                if (string.IsNullOrWhiteSpace(Easy.Common.Config.GetAppSettingsValue("SsoServer")))
                {
                    return;
                }
                string tmptoken = Guid.NewGuid().ToString();
                Session["tmptoken"] = tmptoken;
                string ReturnUrl = Request.Url.Scheme + "://" + Request.Url.Authority + "/sso.ashx";
                ReturnUrl = HttpUtility.UrlEncode(ReturnUrl);
                string additionalparameter = (Request["ReturnUrl"] == null ? "" : "&additionalparameter=" + HttpUtility.UrlEncode(Request["ReturnUrl"]));
                Response.Redirect(Easy.Common.Config.GetAppSettingsValue("SsoServer") + "login.aspx?tmptoken=" + tmptoken + "&ReturnUrl=" + ReturnUrl + additionalparameter + logout);

            }
        }

        protected void btn_login_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(username.Text))
            {
                msg.Text = "登陆名不能为空";
            }
            else if (string.IsNullOrWhiteSpace(password.Text))
            {
                msg.Text = "密码不能为空";
            }
            else
            {
                string loginMsg = (new SystemUserManager()).Login(username.Text, password.Text);
                if (string.IsNullOrWhiteSpace(loginMsg))
                {
                    if (Request["web"] != null)
                        this.Response.Redirect("/mPages/Default.html");
                    else
                        this.Response.Redirect("/default.aspx");
                }
                else
                {
                    msg.Text = loginMsg;
                }
            }
        }


    }
}